package com.example.anyong17_julnumgi;

import java.io.FileOutputStream;
import java.io.ObjectOutputStream.PutField;
import java.text.BreakIterator;
import java.util.ArrayList;



import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.drawable.AnimationDrawable;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.media.AudioManager;
import android.media.SoundPool;
import android.net.rtp.RtpStream;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.Chronometer;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;


public class JUL_Activity extends Activity {
        SensorManager mSm;//센서
        Chronometer mChrono;//크로메타
        TextView mCounterText;//줄넘기 카운터
        TextView mEllapse;
        
        Button mStart;//스타트,스톱 버튼
        Button mSens;//설정 버튼
        TextView mSens_set;
        
        AnimationDrawable mAni;
        int char_sel=1;
        int jul_sel=1;
        
        boolean startFlag;//스타트,스탑 플래그
        
        int sumCount=0;//총 카운터
        int mCounter = 0;//인식한 카운터
        int sufNum =0;//설정 카운터
        
        long mApplyTime ;//센서 타임
        int mSenGap= 700;//센서 갭
        float mSenRange = 16.0f;//센서 범위
        int sSenSpeed = 800;//센서 속도
        
        long mBaseTime;//time워치 start
        long mPauseTime;//time워치 stap
        
        int time_set;
        int count_set;

        int totalSum=0;//총 카운터
        
        Boolean time_OnOff; 
        Boolean count_OnOff; 
        Boolean sound_OnOff;
        
        String lastlap;//정지된 타임 
        String setTimeFomat;
        
        SoundPool mPool;
        int mDdok;
        
        ArrayList<AccelValue> arValue = new ArrayList<AccelValue>();
        ArrayList<Record>arRecord = new ArrayList<Record>();
        
        @Override
        protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.julprocess);
                
                SharedPreferences pref = getSharedPreferences("JUL", 0);//sensor설정
                SharedPreferences set_pref = getSharedPreferences("SET", 0);//time설정
                
                sufNum = pref.getInt("sufNum", 0);//설정
                
                totalSum=pref.getInt("total", 0);
                
                time_set=set_pref.getInt("time_value", 0);
                count_set=set_pref.getInt("count_value", 0);
                time_OnOff=set_pref.getBoolean("time_OnOff", false);
                count_OnOff=set_pref.getBoolean("count_OnOff", false);
                sound_OnOff=set_pref.getBoolean("sound_OnOff", false);
                
                char_sel=pref.getInt("cal_selec", 1);
                jul_sel=pref.getInt("jul_selec", 1);
                
                mSm = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
                mSm.registerListener(mSensorListenr, mSm.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),SensorManager.SENSOR_DELAY_GAME);
                
                mCounterText= (TextView) findViewById(R.id.counter);
                mSens_set=(TextView) findViewById(R.id.jul_sensor_value);
                mSens_set.setText(""+sufNum);
                
                mStart= (Button) findViewById(R.id.jul_start_btn);
                mSens = (Button) findViewById(R.id.jul_sensor_btn);
                
                ImageView img = (ImageView) findViewById(R.id.jul_image);
                
                mEllapse = (TextView) findViewById(R.id.jul_time_view);
                
                if(char_sel<=1)img.setBackgroundResource(R.drawable.rabit);
                if(char_sel==2)img.setBackgroundResource(R.drawable.tutle);
                if(char_sel==3)img.setBackgroundResource(R.drawable.rion);
                if(char_sel==4)img.setBackgroundResource(R.drawable.man);
                if(char_sel==5)img.setBackgroundResource(R.drawable.army);
                if(char_sel==6)img.setBackgroundResource(R.drawable.suq);
                if(char_sel==7)img.setBackgroundResource(R.drawable.dars);
                if(char_sel==8)img.setBackgroundResource(R.drawable.enter);
                
                //img.setBackgroundResource(R.drawable.suq);
                mAni=(AnimationDrawable)img.getBackground();
                
                img.post(new Runnable() {
					
					@Override
					public void run() {
						mAni.stop();
						
					}
				});
                
                if(time_set<10){
                        setTimeFomat =String.format("0%d", time_set);
                }else{setTimeFomat =String.format("%2d", time_set);}
                //setTimeFomat="00:05:00";
        
                mPool= new SoundPool(1,AudioManager.STREAM_MUSIC,0);
                if(jul_sel<=1)mDdok=mPool.load(JUL_Activity.this, R.raw.wood,1);
                if(jul_sel==2)mDdok=mPool.load(JUL_Activity.this, R.raw.plastic,1);
                if(jul_sel==3)mDdok=mPool.load(JUL_Activity.this, R.raw.leep,1);
                if(jul_sel==4)mDdok=mPool.load(JUL_Activity.this, R.raw.iron,1);
                if(jul_sel==5)mDdok=mPool.load(JUL_Activity.this, R.raw.gun,1);
                if(jul_sel==6)mDdok=mPool.load(JUL_Activity.this, R.raw.whip,1);
                if(jul_sel==7)mDdok=mPool.load(JUL_Activity.this, R.raw.sword,1);
                if(jul_sel==8)mDdok=mPool.load(JUL_Activity.this, R.raw.mic,1);
                
                getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
                

                
                
        }

        @Override
        protected void onDestroy() {
                mSm.unregisterListener(mSensorListenr);
                mTime.removeMessages(0);
                RecycleUtils.recursiveRecycle(getWindow().getDecorView());
                System.gc();
         
                super.onDestroy();
        }
        Handler mTime = new Handler(){
                public void handleMessage(Message msg){
                        if(getEllapse().equals(setTimeFomat)){
                                Toast.makeText(JUL_Activity.this, "조건 성립", Toast.LENGTH_LONG).show();
                                mTime.removeMessages(0);
                                startFlag=false;
                                lastlap = getEllapse();
                                rec_clear();
                                showDialog(0);
                        }else{
                        mEllapse.setText(getEllapse());
                        mTime.sendEmptyMessage(0);
                        }
                }
        };
        
         String getEllapse(){
                long now = SystemClock.elapsedRealtime();
                long ell = now - mBaseTime;
                String sEll = String.format("%02d:%02d:%02d", ell/1000/60,(ell/1000)%60,(ell%1000)/10);
                return sEll;
         }
        protected Dialog onCreateDialog(int id){
                
                if(id == 0){
                        return new AlertDialog.Builder(JUL_Activity.this)
                        .setTitle("stop!")
                        .setMessage("줄넘기 개수 : "+sumCount+"\n"+"줄넘기 시간 : "+lastlap)
                        .setPositiveButton("기록보기", new DialogInterface.OnClickListener() {
                                
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                        Intent intent= new Intent(JUL_Activity.this, RecordActivity.class);
                                        Record re = new Record();
                                        re.counter = String.valueOf(sumCount);
                                        re.time = lastlap;
                                        arRecord.add(re);
                                        
                                        intent.putParcelableArrayListExtra("Recoders", arRecord);
                                        startActivity(intent);
                                }
                        })
                        .setNegativeButton("확인", new DialogInterface.OnClickListener() {
                                
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                        Record re = new Record();
                                        re.counter = String.valueOf(sumCount);
                                        re.time = lastlap;
                                        arRecord.add(re);
                                        Toast.makeText(JUL_Activity.this, "저장하였습니다", Toast.LENGTH_SHORT).show();
                                        
                                }
                        })
                        .create();
                }
                return null;
        }
                protected void onPrepareDialog(int id, Dialog dialog) {
                        if(id == 0){
                                        removeDialog(0);
                                        }
                        };
                
        
                
                
                SensorEventListener mSensorListenr = new SensorEventListener() {//센서
                
                @Override
                public void onAccuracyChanged(Sensor sensor, int accuracy) {}
                
                @Override
                public void onSensorChanged(SensorEvent event) {
                        switch (event.sensor.getType()){
                                 case Sensor.TYPE_ACCELEROMETER:
                                         AccelValue av =new AccelValue();
                                         av.value[0]= event.values[0];
                                         av.value[1]= event.values[1];
                                         av.value[2]= event.values[2];
                                         av.time = event.timestamp/10000L;
                                         
                                         arValue.add(av);
                                         
                                         long now = System.currentTimeMillis();
                                         if(now - mApplyTime<mSenGap){
                                                 break;
                                         }
                                         
                                         float[]min = new float[]{100,100,100};
                                         float[]max = new float[]{-100,-100,-100};
                                         for(int i= arValue.size()-1;i>=0;i--){
                                                 AccelValue v = arValue.get(i);
                                                 for(int j = 0;j<3;j++){
                                                         min[j] = Math.min(min[j],v.value[j]);
                                                         max[j] = Math.max(max[j],v.value[j]);
                                                 }
                                                 
                                         }
                                         float[] diff = new float[3];
                                         for(int j=0;j<3;j++){
                                                 diff[j] = Math.abs(max[j]-min[j]);
                                        }
                        
                                        if(diff[0]>mSenRange&&(startFlag==true)){
                                                mApplyTime =now;
                                                mCounter++;
                                                totalSum++;
                                                sumCount=mCounter+sufNum;    
                                                	if(sumCount==count_set&&count_OnOff==true){
	                                                        mTime.removeMessages(0);
	                                                        startFlag=false;
	                                                        lastlap = getEllapse();
	                                                        rec_clear();
	                                                        showDialog(0);
	                                                }
                                                if(sound_OnOff==true){
                                                mPool.play(mDdok, 1, 1, 0, 0, 2);
                                                }
                                                mCounterText.setText(""+sumCount);
                                                arValue.clear();
                                        }
                        }
                }
        };//센서 리스터 끝
        public void mOnClick(View v){
                switch(v.getId()){
                        
                        case R.id.jul_start_btn:
                                if(startFlag==false){
                                mStart.setBackgroundResource(R.drawable.jul_stop);
                                mBaseTime= SystemClock.elapsedRealtime();
                                mTime.sendEmptyMessage(0);
                                mAni.start();
                                //Toast.makeText(JUL_Activity.this, "Stop"+sufNum, Toast.LENGTH_LONG).show();
                                startFlag=true;
                                }else{
                                        //Toast.makeText(JUL_Activity.this, "start"+sufNum, Toast.LENGTH_LONG).show();
                                        mTime.removeMessages(0);
                                        startFlag=false;
                                        lastlap = getEllapse();
                                        rec_clear();
                                        showDialog(0);
                                        
                                        
                                }
                                break;
                        case R.id.jul_sensor_btn:
                                startActivity(new Intent(this, SensorSetActivity.class));
                                break;
                        
                }
        }
        public void rec_clear(){
                mStart.setBackgroundResource(R.drawable.jul_start);
                mCounterText.setText("0");
                mCounter = 0;
                mTime.removeMessages(0);
                mEllapse.setText("00:00:00");
                mAni.stop();
        }
        @Override
        protected void onPause() {
                super.onPause();
                SharedPreferences pref = getSharedPreferences("JUL", 0);
                SharedPreferences.Editor edit = pref.edit();
                
                edit.putInt("total", totalSum);
                
                edit.commit();
        
                finish();
        }
        
        @Override
        protected void onResume() {
                super.onResume();
                mCounterText.setText("0");
                mCounter = 0;//초기화
        }
        @Override
        protected void onRestart() {
                super.onRestart();
                SharedPreferences pref = getSharedPreferences("JUL", 0);
                sufNum = pref.getInt("sufNum", 0);
                mSens_set.setText(""+sufNum);
        }
        
}